<?php
/**
 * 节点路径控件
 * <pre>
 * $this->widget('lib.widgets.tree.CNodePath', array(
 *  // 当前节点
 *  'model' => EnumPca::model()->findByPk(5),
 *  // 取值字段，用于显示
 *  'valueAttribute' => 'name',
 * ));
 * </pre>
 * @author yangdongqi <yangdongqi@hayzone.com>
 * @package lib.widgets.tree
 */
class CNodePath extends CWidget {
	/**
	 * 树形model实例
	 * @var CActiveRecord
	 */
	public $model;
	
	/**
	 * 每一个节点model的取值字段
	 * @var string
	 */
	public $valueAttribute;
	
	/**
	 * 节点分隔符
	 * @var string
	 */
	public $separator = ' > ';
	
	/**
	 * 当返回值为空的时候，输出的字符
	 * @var string
	 */
	public $empty = '无';
	
	/**
	 * 是否设置返回
	 * @var boolean 设置为true，则不在run方法输出结果
	 */
	public $return = false;
	
	/**
	 * 渲染后的结果
	 * @var string
	 */
	protected $_result = '';
	
	public function run() {
		
		if(!$this->model) return $this->echoEmpty();
		
		(array)$models = $this->model->ancestors;
		if(!$models) return $this->echoEmpty();
		
		$nodeHtmls = array();
		
		foreach($models as $model) {
			$nodeHtmls[] = $this->createNodeHtml($model);
		}
		
		$this->_result = implode(CHtml::encode($this->separator), $nodeHtmls);
		if(!$this->return)
			echo $this->_result;
	}
	
	protected function createNodeHtml($node) {
		return $node->{$this->valueAttribute};
	}
	
	
	protected function echoEmpty() {
		$this->_result = $this->empty;
		if(!$this->return)
			echo $this->_result;
	}
	
	public function getResult() {
		return $this->_result;
	}
	
	public function __toString() {
		return $this->getResult();
	}
}

?>